package ar.com.santiagobasulto.crawler.core;

import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;

public class Parser extends HTMLEditorKit.ParserCallback {

	protected URL base;
	protected URLFinder finder;

	public Parser(URL base, URLFinder finder)
	{
		this.base = base;
		this.finder = finder;
	}
	public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a,int pos){
		//System.out.println(t);

		String href = (String)a.getAttribute(HTML.Attribute.HREF);

		if((href==null) && (t==HTML.Tag.FRAME) ){
			href = (String)a.getAttribute(HTML.Attribute.SRC);
		}

		if ( href==null ){

			return;
		}

		int i = href.indexOf('#');
		if ( i!=-1 )
			href = href.substring(0,i);
		handleLink(base,href);
	}

	public void handleStartTag(HTML.Tag t, MutableAttributeSet a,int pos)
	{
		handleSimpleTag(t,a,pos);    // handle the same way
	}

  protected void handleLink(URL base,String str)
  {
    try {
      URL url = new URL(base,str);
      this.finder.offer(url);
    }catch ( MalformedURLException e ) {
    	System.out.println("Found malformed URL: " + str );
    }
  }
}